﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace eCompany.Forms
{
    public partial class company_form : Form
    {
        private eCompany.eObj.company m_company = null;
        private eCompany.eObj.currency_list m_cl = null;

        private Thread m_RefreshEmployeeThread = null;
        private delegate void stopLoadHandler(bool reload);
        private stopLoadHandler stopLoadDelegate;

        public company_form(eCompany.eObj.company c, eCompany.eObj.currency_list cl)
        {
            InitializeComponent();
            stopLoadDelegate = new stopLoadHandler(this.RefreshEmployeeListStopped);
            this.Icon = pics.eCompanyIcon;
            m_company = c;
            m_cl = cl;
        }

        private void LoadImageList()
        {
            foreach (eCompany.eObj.currency cur in m_cl.currencies)
            {
                currencyImageList.Images.Add(cur.short_name, Tools.GetCurrencyImage(cur.short_name));
            }

            foreach (eCompany.eObj.company_type_enum cte in Enum.GetValues(typeof(eCompany.eObj.company_type_enum)))
            {
                Image img = Tools.GetCompanyTypeImage(cte);
                if (img != null)
                    currencyImageList.Images.Add("ct_" + cte.ToString(), img);
            }
        }

        private void RefreshEmployeeTab2()
        {
            employeetableLayoutPanelExtended.SuspendLayout();
            foreach (Control ctrl in employeetableLayoutPanelExtended.Controls)
            {
                ctrl.Dispose();
            }
            employeetableLayoutPanelExtended.Controls.Clear();
            foreach (eCompany.eObj.employee e in m_company.employee_list)
            {
                if (e.date_out == null)
                {
                    eCompany.Custom_Controls.big_employee_ctrl ctrl = new Custom_Controls.big_employee_ctrl(m_company, e.id, m_cl);
                    ctrl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
                    ctrl.SetCollapseState(true);
                    employeetableLayoutPanelExtended.Controls.Add(ctrl);
                }
            }
            employeetableLayoutPanelExtended.ResumeLayout();
        }

        private void RefreshShopTab()
        {
            eManager.eManager eM = new eManager.eManager();
            shopsTableLayoutPanelExtended.SuspendLayout();
            foreach (Control ctrl in shopsTableLayoutPanelExtended.Controls)
            {
                ctrl.Dispose();
            }
            shopsTableLayoutPanelExtended.Controls.Clear();
            foreach (eCompany.eObj.shop s in m_company.shops)
            {
                eCompany.Custom_Controls.big_shop_ctrl ctrl = new Custom_Controls.big_shop_ctrl(m_company, s.currency, m_cl);
                ctrl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
                ctrl.SetCollapseState(true);
                if (eM.getAccount(m_company, Guid.Parse(m_company.default_account)).currency == s.currency)
                    ctrl.SetCollapseState(false);
                shopsTableLayoutPanelExtended.Controls.Add(ctrl);
            }
            shopsTableLayoutPanelExtended.ResumeLayout();
        }

        private void RefreshStockTab()
        {
            companyStockListView.BeginUpdate();
            companyStockListView.Items.Clear();

            eManager.eManager eM = new eManager.eManager();
            double today_volume_in = 0;
            double today_volume_out = 0;
            double today_cost = 0;
            double yesterday_volume_in = 0;
            double yesterday_volume_out = 0;
            double yesterday_cost = 0;
            double before_volume_in = 0;
            double before_volume_out = 0;

            ListViewGroup today_group = new ListViewGroup();
            ListViewGroup before_group = new ListViewGroup();
            ListViewGroup yesterday_group = new ListViewGroup();
            companyStockListView.Groups.Add(before_group);
            companyStockListView.Groups.Add(yesterday_group);
            companyStockListView.Groups.Add(today_group);

            foreach (eCompany.eObj.stock s in m_company.company_stock)
            {
                ListViewItem item = new ListViewItem();

                item.Text = s.date.ToString("d");
                item.SubItems.Add(eManager.eManager.formatDouble(s.volume_in));
                item.SubItems.Add(eManager.eManager.formatDouble(s.volume_out));
                item.SubItems.Add(eManager.eManager.formatDouble(s.production_cost) + eM.getAccount(m_company, Guid.Parse(m_company.default_account)).currency);
                if(s.employee!=null)
                    item.SubItems.Add(eM.getEmployee(m_company,Guid.Parse(s.employee)).name);
                if (DateTime.Today == s.date.Date)
                {
                    today_volume_in += s.volume_in;
                    today_volume_out += s.volume_out;
                    today_cost += s.volume_in * s.production_cost;
                    item.Group = today_group;
                }
                else if (DateTime.Today.AddDays(-1) == s.date.Date)
                {
                    yesterday_volume_in += s.volume_in;
                    yesterday_volume_out += s.volume_out;
                    yesterday_cost += s.volume_in * s.production_cost;
                    item.Group = yesterday_group;
                }
                else
                {
                    before_volume_in += s.volume_in;
                    before_volume_out += s.volume_out;
                    item.Group = before_group;
                }
                if (s.volume_out<s.volume_in)
                    item.Font = new Font(item.Font.FontFamily, item.Font.Size, FontStyle.Bold);

                companyStockListView.Items.Add(item);
            }
            today_cost = today_cost / today_volume_in;
            yesterday_cost = yesterday_cost / yesterday_volume_in;
            today_group.Header = "Today (in=" + eCompany.eManager.eManager.formatDouble(today_volume_in) +
                            "    out=" + eCompany.eManager.eManager.formatDouble(today_volume_out) +
                            "    net=" + eCompany.eManager.eManager.formatDouble(today_volume_in-today_volume_out)+
                            "    cost="+ eCompany.eManager.eManager.formatDouble(today_cost)+")";
            yesterday_group.Header = "Yesterday (in=" + eCompany.eManager.eManager.formatDouble(yesterday_volume_in) +
                            "    out=" + eCompany.eManager.eManager.formatDouble(yesterday_volume_out)+
                            "    net=" + eCompany.eManager.eManager.formatDouble(yesterday_volume_in - yesterday_volume_out) +
                            "    cost=" + eCompany.eManager.eManager.formatDouble(yesterday_cost) + ")";
            before_group.Header = "Before Today (in=" + eCompany.eManager.eManager.formatDouble(before_volume_in) +
                            "    out=" + eCompany.eManager.eManager.formatDouble(before_volume_out) +
                            "    net=" + eCompany.eManager.eManager.formatDouble(before_volume_in-before_volume_out)+")";
            companyStockListView.SetGroupState(ListViewGroupState.Collapsible | ListViewGroupState.Collapsed);
            companyStockListView.EndUpdate();
        }

        private void InitTabs()
        {

            companyTabControl.Visible = false;
            foreach (TabPage tp in companyTabControl.TabPages)
            {
                if (tp.Tag.ToString().StartsWith("static") != true)
                    companyTabControl.TabPages.Remove(tp);
            }

            foreach (eObj.account acc in m_company.account_list)
            {
                TabPage tp = new TabPage();
                tp.Text = "Account " + acc.currency;
                tp.Tag = "account" + acc.currency + "Tab";
                tp.BackColor = Color.White;

                account_ctrl ctrl = new account_ctrl(m_company,acc, m_cl);
                ctrl.Top = 7;
                ctrl.Left = 7;
                ctrl.Width = tp.Width - 13;
                ctrl.Height = tp.Height - 13;
                ctrl.Margin = new System.Windows.Forms.Padding(3, 3, 3, 3);
                ctrl.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                tp.Controls.Add(ctrl);

                companyTabControl.TabPages.Add(tp);
                tp.ImageKey = acc.currency;
            }

            foreach (eObj.material_stock ms in m_company.material_list)
            {
                eCompany.eManager.eManager eM = new eManager.eManager();
                TabPage tp = new TabPage();
                tp.Text = "Raw " + ms.material_type.ToString();
                tp.Tag = "raw" + ms.material_type.ToString() + "Tab";
                tp.BackColor = Color.White;

                raw_ctrl ctrl = new raw_ctrl(m_company, eM.getAccount(m_company,Guid.Parse(m_company.default_account)).currency,ms.material_type, m_cl);
                ctrl.Top = 7;
                ctrl.Left = 7;
                ctrl.Width = tp.Width - 13;
                ctrl.Height = tp.Height - 13;
                ctrl.Margin = new System.Windows.Forms.Padding(3, 3, 3, 3);
                ctrl.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                tp.Controls.Add(ctrl);

                companyTabControl.TabPages.Add(tp);
            }

            //Remove by adding new tab page for shop
            //foreach (eObj.shop s in m_company.shops)
            //{
            //    TabPage tp = new TabPage();
            //    tp.Text = "Shop " + s.currency;
            //    tp.Tag = "shop" + s.currency + "Tab";
            //    tp.BackColor = Color.White;

            //    shop_ctrl ctrl = new shop_ctrl(m_company, s.currency, m_cl);
            //    ctrl.Top = 7;
            //    ctrl.Left = 7;
            //    ctrl.Width = tp.Width - 13;
            //    ctrl.Height = tp.Height - 13;
            //    ctrl.Margin = new System.Windows.Forms.Padding(3, 3, 3, 3);
            //    ctrl.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
            //    tp.Controls.Add(ctrl);

            //    companyTabControl.TabPages.Add(tp);
            //    tp.ImageKey = s.currency;
            //}
            companyTabControl.Visible = true;
        }

        private void RefreshGeneralTab()
        {
            eCompany.eManager.eManager eM = new eManager.eManager();

            addNewShopToolStripComboBox.Items.Clear();
            foreach (eCompany.eObj.currency c in m_cl.currencies)
            {
                eCompany.eObj.shop s = eM.getShop(m_company, c.short_name);
                if (s == null)
                    addNewShopToolStripComboBox.Items.Add(c.short_name);
            }

            generalListView.BeginUpdate();
            generalListView.Items.Clear();
            ListViewGroup grp = generalListView.Groups.Add("ACCOUNTS", "Accounts");
            foreach (eCompany.eObj.account acc in m_company.account_list)
            {
                double acc_value = 0;
                double acc_gld_value = 0;
                double old_acc_value = 0;
                double old_gld_value = 0;

                acc_value = eM.getAccountValue(acc);
                old_acc_value = eM.getAccountValue(acc, DateTime.Today.AddDays(-1));
                if (acc.currency != "GLD")
                {
                    acc_gld_value = eM.currencyToGOLD(m_cl, acc.currency, acc_value);
                    old_gld_value = eM.currencyToGOLD(m_cl, acc.currency, old_acc_value);
                }
                else
                {
                    acc_gld_value = acc_value;
                    old_gld_value = old_acc_value;
                }

                ListViewItem item = new ListViewItem();
                item.Group = grp;
                item.ImageKey = acc.currency;
                item.Text = "Account " + acc.currency;
                item.SubItems.Add("");
                item.SubItems.Add(eCompany.eManager.eManager.formatDouble(acc_value)+ acc.currency+
                    " ("+
                    eCompany.eManager.eManager.formatDouble(acc_value-old_acc_value) + ")");
                item.SubItems.Add(eCompany.eManager.eManager.formatDouble(acc_gld_value) +
                    "G"+
                    " ("+eCompany.eManager.eManager.formatDouble(acc_gld_value-old_gld_value)+")");
                if (acc.id == m_company.default_account)
                    item.Font = new Font(item.Font.FontFamily, item.Font.Size, FontStyle.Bold);
                generalListView.Items.Add(item);
                generalListView.EndUpdate();
            }

            grp = generalListView.Groups.Add("STOCK", "Company Stock");
            foreach (eCompany.eObj.material_stock ms in m_company.material_list)
            {
                double raw_count = eM.getMaterialCount(m_company, ms.material_type);
                double raw_value = eM.getMaterialValue(m_company, ms.material_type);
                double raw_gld_value = eM.currencyToGOLD(m_cl, eM.getAccount(m_company, Guid.Parse(m_company.default_account)).currency, raw_value);

                ListViewItem raw_item = new ListViewItem();
                raw_item.Group = grp;
                raw_item.ImageKey = "ct_" + ms.material_type.ToString();
                raw_item.Text = "Raw " + ms.material_type.ToString();
                raw_item.SubItems.Add(eCompany.eManager.eManager.formatDouble(raw_count) + " items");
                raw_item.SubItems.Add(eCompany.eManager.eManager.formatDouble(raw_value) + eM.getAccount(m_company, Guid.Parse(m_company.default_account)).currency);
                raw_item.SubItems.Add(eCompany.eManager.eManager.formatDouble(raw_gld_value) + "G");
                generalListView.Items.Add(raw_item);
            }                
            
            double comp_stock_count = eM.getStockCount(m_company);
            double comp_stock_value = eM.getStockValue(m_company);
            double comp_gld_stock_value = eM.currencyToGOLD(m_cl, eM.getAccount(m_company, Guid.Parse(m_company.default_account)).currency, comp_stock_value) ;
            ListViewItem item_stock = new ListViewItem();
            item_stock.Group = grp;
            item_stock.ImageKey = "ct_" + m_company.type.ToString();
            item_stock.Text = "Stock";
            item_stock.SubItems.Add(eManager.eManager.formatDouble(comp_stock_count) + " items");
            item_stock.SubItems.Add(eCompany.eManager.eManager.formatDouble(comp_stock_value) + eM.getAccount(m_company, Guid.Parse(m_company.default_account)).currency);
            item_stock.SubItems.Add(eCompany.eManager.eManager.formatDouble(comp_gld_stock_value) + "G");
            generalListView.Items.Add(item_stock);

            grp = generalListView.Groups.Add("SHOPS", "Company Shops");
            foreach (eCompany.eObj.shop s in m_company.shops)
            {
                double shop_stock = eM.getShopStock(m_company, s.currency);
                double shop_value = eM.getShopValue(m_company, s.currency);
                double shop_gld_value = eM.currencyToGOLD(m_cl, s.currency, shop_value);

                ListViewItem shop_item = new ListViewItem();
                shop_item.ImageKey = s.currency;
                shop_item.Group = grp;
                shop_item.Text = "Shop " + s.currency;
                shop_item.SubItems.Add(shop_stock.ToString() + " items");
                shop_item.SubItems.Add(eManager.eManager.formatDouble(shop_value) + s.currency);
                shop_item.SubItems.Add(eManager.eManager.formatDouble(shop_gld_value) + "G");
                generalListView.Items.Add(shop_item);
            }

            generalListView.SetGroupState(ListViewGroupState.Collapsible);
        }

        public void InitGraph()
        {
            eCompany.eManager.eManager eM = new eManager.eManager();
            List<eCompany.eManager.ChartItem> lst = eM.getCompanyAccountChartValue(m_company, m_cl);

            System.Windows.Forms.DataVisualization.Charting.Series serie = companyChart.Series[0];
            foreach (eCompany.eManager.ChartItem item in lst)
            {
                serie.Points.AddXY(item.date, item.volume);
            }
        }

        public void refreshGraph()
        {
            companyChart.Series[0].Points.Clear();
            InitGraph();
        }

        private void refreshAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshAll();
        }

        public void RefreshAll()
        {
            RefreshGeneralTab();
            refreshGraph();
            RefreshStockTab();
            InitTabs();
        }

        private void addNewShopToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            eCompany.eManager.eManager eM = new eManager.eManager();
            eM.addShop(m_company, addNewShopToolStripComboBox.Text, 0);
            InitTabs();
            RefreshGeneralTab();
            refreshGraph();
        }

        private void updateCustomizationCmd_Click(object sender, EventArgs e)
        {
            string str_newCustomPoints = "";

            if (Tools.InputBox("Modify Custom Points", "New custom points", ref str_newCustomPoints) == System.Windows.Forms.DialogResult.OK)
            {
                int newCustomPoint;

                if(int.TryParse(str_newCustomPoints,out newCustomPoint))
                {
                    m_company.customized_point = newCustomPoint;
                    //customPointLbl.Text = str_newCustomPoints;
                    //customPointsProgressBar.Value = newCustomPoint;
                }
            }
        }

        private void addNewAccountToolStripMenuItem_Click(object sender, EventArgs e)
        {
            eCompany.Forms.add_new_account_form f = new Forms.add_new_account_form(m_company, m_cl);
            f.ShowDialog();
            this.RefreshGeneralTab();
            this.refreshGraph();
            this.InitTabs();
        }

        private void refreshAllToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            this.RefreshGeneralTab();
            this.refreshGraph();
            this.InitTabs();
        }

        private void lblCompanyNameLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string str = "http://economy.erepublik.com/en/company/" + m_company.name.Replace(" ","-") + "/" + m_company.api_id;
            str = Uri.EscapeUriString(str);
            System.Diagnostics.Process.Start(str);
        }

        private void company_form_Load(object sender, EventArgs e)
        {
            //Getting company id if we don't have it
            if (m_company.api_id == null || m_company.api_id == "")
            {
                string new_api_id = "";
                if (Tools.InputBox("eAPI - " + m_company.name + " company ID", "We don't have your company api ID. Please enter it :", ref new_api_id) == DialogResult.OK)
                {
                    m_company.api_id = new_api_id;
                }
            }

            this.Text = m_company.name;
            lblCompanyNameLink.Text = m_company.name;
            if (m_company.api_id == null)
                lblCompanyNameLink.Enabled = false;
            companyTypePictureBox.Image = Tools.GetCompanyTypeImage(m_company.type);
            company_detailPanel.Visible = false;
            if (!eCompany.eRules.eCompanyRules.isMaterialCompanyType(m_company.type))
            {
                customLevelPB.Image = Tools.GetCustomLevelImage(m_company.customized_level);
                //customPointLbl.Text = m_company.customized_point.ToString();
                //customPointsProgressBar.Value = m_company.customized_point;
                company_detailPanel.Visible = true;
            }

            LoadImageList();
            InitTabs();
            RefreshGeneralTab();
            InitGraph();
            RefreshStockTab();
            
            RefreshEmployeeTab2();
            RefreshShopTab();

//#if DEBUG
//            eApi.api eApi = new eApi.api();
//            Dictionary<string,string> tab = new Dictionary<string,string>();
//            tab.Add("health", "80");
//            double volume = 0;
//            double price = 0;
//            eApi.getMarketForCompany(eRules.eCompanyRules.getIndustryId(m_company.type).ToString(), "11", tab, out volume, out price);
//#endif
        }

        private void RefreshEmployeeList(object o)
        {
            try
            {
                eApi.api _api = new eApi.api();
                List<string> id_list = _api.loadCompanyEmployeeListFromWeb(m_company.api_id);
                bool bNewEmp = false;
                eManager.eManager eM = new eManager.eManager();

                foreach (string id in id_list)
                {
                    eObj.employee emp = eM.getEmployeeByApiId(m_company, id, true);
                    if (emp == null || emp.date_out != null)
                    {
                        // New employee !
                        eApi.apiEmployee apiE = _api.loadCitizenFromWeb(id, "");
                        emp = new eObj.employee();
                        emp.id = Guid.NewGuid().ToString();
                        emp.name = apiE.name;
                        emp.date_in = DateTime.Now;
                        emp.api_id = id;

                        m_company.employee_list.Add(emp);
                        bNewEmp = true;
                    }
                }
                if (bNewEmp == true)
                {
                    MessageBox.Show("You have new employee.", "Employee Synchronization", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Invoke(this.stopLoadDelegate, new Object[] { true });
                }
                else
                {
                    MessageBox.Show("You have no new employee.", "Employee Synchronization", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Invoke(this.stopLoadDelegate, new Object[] { false });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading company : " + ex.Message, "Employee Synchronization", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Invoke(this.stopLoadDelegate, new Object[] { false });
            }
        }

        private void RefreshEmployeeListStopped(bool reload)
        {
            if(reload == true)
                RefreshEmployeeTab2();

            //employeetableLayoutPanelExtended.Enabled = true;
            syncPB.Image = pics.button_synchronize;
            this.Cursor = Cursors.Default;
        }

        [PreEmptive.Attributes.Feature("API.RefreshEmployeeList")]
        private void syncPB_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            syncPB.Image = pics.LOADER_SMALL;
            //employeetableLayoutPanelExtended.Enabled = false;

            if (m_company.api_id != null && m_company.api_id != "")
            {
                m_RefreshEmployeeThread = new Thread(RefreshEmployeeList);
                m_RefreshEmployeeThread.Start(m_company.api_id);
            }
        }
    }
}
